using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;

public class HighlightManager : MonoBehaviour
{
    [Header("高光时刻设置")]
    public bool enableHighlights = true;
    public bool autoCapture = true;
    public float captureBufferTime = 5f; // 捕获前N秒的内容
    public int maxHighlights = 10;
    public float minHighlightInterval = 10f; // 最小间隔时间
    
    [Header("触发条件")]
    public HighlightTrigger[] triggers;
    
    [Header("录制设置")]
    public int recordingFPS = 30;
    public int recordingWidth = 1920;
    public int recordingHeight = 1080;
    public float maxRecordingDuration = 30f;
    public bool compressRecordings = true;
    
    [Header("存储设置")]
    public string highlightFolder = "Highlights";
    public bool saveToCloud = false;
    public bool autoShare = false;
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    public bool simulateRecording = true; // 测试模式
    
    // 单例模式
    public static HighlightManager Instance { get; private set; }
    
    // 高光时刻数据
    private List<HighlightMoment> highlights;
    private Queue<GameFrame> frameBuffer;
    private bool isRecording = false;
    private float lastHighlightTime = 0f;
    private int highlightCounter = 0;
    
    // 事件
    public event Action<HighlightMoment> OnHighlightCaptured;
    public event Action<HighlightMoment> OnHighlightSaved;
    public event Action<string> OnHighlightError;
    
    [System.Serializable]
    public class HighlightTrigger
    {
        public string triggerName;
        public HighlightType type;
        public float threshold;
        public bool enabled = true;
        public float priority = 1f;
        public string description;
    }
    
    [System.Serializable]
    public class HighlightMoment
    {
        public string id;
        public HighlightType type;
        public float timestamp;
        public float duration;
        public string title;
        public string description;
        public GameStats statsAtMoment;
        public string filePath;
        public bool isSaved;
        public float rating;
    }
    
    [System.Serializable]
    public class GameFrame
    {
        public float timestamp;
        public Vector3 playerPosition;
        public int enemyCount;
        public int bulletCount;
        public float playerHealth;
        public int score;
        public List<string> activeEffects;
    }
    
    [System.Serializable]
    public class GameStats
    {
        public int score;
        public int wave;
        public int lives;
        public float health;
        public int enemiesKilled;
        public int bulletsShot;
        public float accuracy;
        public List<string> activePowerUps;
    }
    
    public enum HighlightType
    {
        MultiKill,          // 连续击杀
        NearDeath,          // 濒死逃脱
        PerfectWave,        // 完美通关
        PowerUpCombo,       // 道具连击
        BossDefeat,         // 击败Boss
        HighScore,          // 高分时刻
        CloseCall,          // 险象环生
        ScreenClear,        // 清屏时刻
        LongSurvival,       // 长时间生存
        AccuracyStreak      // 精准射击
    }
    
    void Awake()
    {
        // 单例模式实现
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeHighlightManager();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void InitializeHighlightManager()
    {
        highlights = new List<HighlightMoment>();
        frameBuffer = new Queue<GameFrame>();
        
        // 创建默认触发器
        if (triggers == null || triggers.Length == 0)
        {
            CreateDefaultTriggers();
        }
        
        // 创建高光时刻文件夹
        CreateHighlightDirectory();
        
        // 订阅游戏事件
        SubscribeToGameEvents();
        
        // 开始帧缓冲
        if (enableHighlights && autoCapture)
        {
            StartCoroutine(FrameBufferCoroutine());
        }
        
        Debug.Log($"高光时刻管理器已初始化 - 自动捕获: {autoCapture}");
    }
    
    void CreateDefaultTriggers()
    {
        triggers = new HighlightTrigger[]
        {
            new HighlightTrigger
            {
                triggerName = "MultiKill",
                type = HighlightType.MultiKill,
                threshold = 5f, // 5秒内击杀多个敌人
                enabled = true,
                priority = 0.9f,
                description = "短时间内击杀多个敌人"
            },
            new HighlightTrigger
            {
                triggerName = "NearDeath",
                type = HighlightType.NearDeath,
                threshold = 0.1f, // 生命值低于10%
                enabled = true,
                priority = 0.8f,
                description = "生命值极低时的精彩表现"
            },
            new HighlightTrigger
            {
                triggerName = "PerfectWave",
                type = HighlightType.PerfectWave,
                threshold = 1f, // 无伤通关
                enabled = true,
                priority = 0.95f,
                description = "无伤完成波次"
            },
            new HighlightTrigger
            {
                triggerName = "PowerUpCombo",
                type = HighlightType.PowerUpCombo,
                threshold = 3f, // 同时激活3个道具
                enabled = true,
                priority = 0.7f,
                description = "多个道具同时激活"
            },
            new HighlightTrigger
            {
                triggerName = "HighScore",
                type = HighlightType.HighScore,
                threshold = 10000f, // 达到高分
                enabled = true,
                priority = 0.6f,
                description = "达到新的高分记录"
            }
        };
    }
    
    void CreateHighlightDirectory()
    {
        string path = Path.Combine(Application.persistentDataPath, highlightFolder);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            if (showDebugInfo)
            {
                Debug.Log($"创建高光时刻文件夹: {path}");
            }
        }
    }
    
    void SubscribeToGameEvents()
    {
        // 订阅游戏管理器事件
        if (GameManager.Instance != null)
        {
            GameManager.Instance.OnScoreChanged += OnScoreChanged;
            GameManager.Instance.OnPlayerDied += OnPlayerDied;
        }
        
        // 订阅宝箱生成器事件
        TreasureSpawner treasureSpawner = FindObjectOfType<TreasureSpawner>();
        if (treasureSpawner != null)
        {
            // 这里可以添加宝箱击杀事件的订阅
        }
    }
    
    IEnumerator FrameBufferCoroutine()
    {
        while (enableHighlights)
        {
            if (GameManager.Instance != null && GameManager.Instance.GetCurrentState() == GameManager.GameState.Playing)
            {
                CaptureCurrentFrame();
            }
            
            yield return new WaitForSeconds(1f / recordingFPS);
        }
    }
    
    void CaptureCurrentFrame()
    {
        GameFrame frame = new GameFrame
        {
            timestamp = Time.time,
            playerPosition = GetPlayerPosition(),
            enemyCount = GetEnemyCount(),
            bulletCount = GetBulletCount(),
            playerHealth = GetPlayerHealth(),
            score = GameManager.Instance?.GetScore() ?? 0,
            activeEffects = GetActiveEffects()
        };
        
        frameBuffer.Enqueue(frame);
        
        // 保持缓冲区大小
        int maxFrames = Mathf.RoundToInt(captureBufferTime * recordingFPS);
        while (frameBuffer.Count > maxFrames)
        {
            frameBuffer.Dequeue();
        }
    }
    
    Vector3 GetPlayerPosition()
    {
        PlayerController player = FindObjectOfType<PlayerController>();
        return player != null ? player.transform.position : Vector3.zero;
    }
    
    int GetEnemyCount()
    {
        return FindObjectsOfType<EnemyController>().Length;
    }
    
    int GetBulletCount()
    {
        return FindObjectsOfType<BulletController>().Length;
    }
    
    float GetPlayerHealth()
    {
        PlayerController player = FindObjectOfType<PlayerController>();
        return player != null ? player.GetCurrentHealth() : 0f;
    }
    
    List<string> GetActiveEffects()
    {
        List<string> effects = new List<string>();
        
        PowerUpManager powerUpManager = FindObjectOfType<PowerUpManager>();
        if (powerUpManager != null)
        {
            // 这里可以获取当前激活的道具效果
            effects.Add("PowerUps");
        }
        
        return effects;
    }
    
    // 检查高光时刻触发条件
    void CheckHighlightTriggers()
    {
        if (!enableHighlights || Time.time - lastHighlightTime < minHighlightInterval)
        {
            return;
        }
        
        foreach (var trigger in triggers)
        {
            if (!trigger.enabled) continue;
            
            bool shouldTrigger = false;
            
            switch (trigger.type)
            {
                case HighlightType.MultiKill:
                    shouldTrigger = CheckMultiKillTrigger(trigger.threshold);
                    break;
                    
                case HighlightType.NearDeath:
                    shouldTrigger = CheckNearDeathTrigger(trigger.threshold);
                    break;
                    
                case HighlightType.PerfectWave:
                    shouldTrigger = CheckPerfectWaveTrigger();
                    break;
                    
                case HighlightType.PowerUpCombo:
                    shouldTrigger = CheckPowerUpComboTrigger((int)trigger.threshold);
                    break;
                    
                case HighlightType.HighScore:
                    shouldTrigger = CheckHighScoreTrigger(trigger.threshold);
                    break;
            }
            
            if (shouldTrigger)
            {
                TriggerHighlight(trigger);
                break; // 一次只触发一个高光时刻
            }
        }
    }
    
    bool CheckMultiKillTrigger(float timeWindow)
    {
        // 检查时间窗口内的击杀数量
        // 这里需要实际的击杀事件数据
        return false; // 占位符
    }
    
    bool CheckNearDeathTrigger(float healthThreshold)
    {
        float currentHealth = GetPlayerHealth();
        PlayerController player = FindObjectOfType<PlayerController>();
        if (player != null)
        {
            float maxHealth = player.GetMaxHealth();
            return (currentHealth / maxHealth) <= healthThreshold;
        }
        return false;
    }
    
    bool CheckPerfectWaveTrigger()
    {
        // 检查是否无伤完成波次
        // 这里需要波次完成事件和伤害记录
        return false; // 占位符
    }
    
    bool CheckPowerUpComboTrigger(int minPowerUps)
    {
        PowerUpManager powerUpManager = FindObjectOfType<PowerUpManager>();
        if (powerUpManager != null)
        {
            // 检查同时激活的道具数量
            return powerUpManager.activePowerUps.Count >= minPowerUps; // 直接访问PowerUpManager中的activePowerUps列表
        }
        return false;
    }
    
    bool CheckHighScoreTrigger(float scoreThreshold)
    {
        int currentScore = GameManager.Instance?.GetScore() ?? 0;
        return currentScore >= scoreThreshold;
    }
    
    void TriggerHighlight(HighlightTrigger trigger)
    {
        if (highlights.Count >= maxHighlights)
        {
            // 移除最旧的高光时刻
            RemoveOldestHighlight();
        }
        
        HighlightMoment moment = CreateHighlightMoment(trigger);
        highlights.Add(moment);
        
        lastHighlightTime = Time.time;
        
        if (showDebugInfo)
        {
            Debug.Log($"触发高光时刻: {trigger.triggerName} - {moment.title}");
        }
        
        OnHighlightCaptured?.Invoke(moment);
        
        // 开始录制
        if (autoCapture)
        {
            StartCoroutine(RecordHighlight(moment));
        }
    }
    
    HighlightMoment CreateHighlightMoment(HighlightTrigger trigger)
    {
        highlightCounter++;
        
        return new HighlightMoment
        {
            id = $"highlight_{highlightCounter}_{DateTime.Now:yyyyMMdd_HHmmss}",
            type = trigger.type,
            timestamp = Time.time,
            duration = captureBufferTime + 5f, // 额外录制5秒
            title = GetHighlightTitle(trigger.type),
            description = trigger.description,
            statsAtMoment = GetCurrentGameStats(),
            isSaved = false,
            rating = trigger.priority
        };
    }
    
    string GetHighlightTitle(HighlightType type)
    {
        switch (type)
        {
            case HighlightType.MultiKill: return "连续击杀";
            case HighlightType.NearDeath: return "濒死逃脱";
            case HighlightType.PerfectWave: return "完美通关";
            case HighlightType.PowerUpCombo: return "道具连击";
            case HighlightType.BossDefeat: return "击败Boss";
            case HighlightType.HighScore: return "高分时刻";
            case HighlightType.CloseCall: return "险象环生";
            case HighlightType.ScreenClear: return "清屏时刻";
            case HighlightType.LongSurvival: return "长时间生存";
            case HighlightType.AccuracyStreak: return "精准射击";
            default: return "精彩时刻";
        }
    }
    
    GameStats GetCurrentGameStats()
    {
        return new GameStats
        {
            score = GameManager.Instance?.GetScore() ?? 0,
            wave = EnemySpawner.Instance?.GetCurrentWave() ?? 0,
            lives = GameManager.Instance?.GetLives() ?? 0,
            health = GetPlayerHealth(),
            enemiesKilled = 0, // 需要实际数据
            bulletsShot = 0, // 需要实际数据
            accuracy = 0f, // 需要实际数据
            activePowerUps = GetActiveEffects()
        };
    }
    
    IEnumerator RecordHighlight(HighlightMoment moment)
    {
        if (simulateRecording)
        {
            // 模拟录制过程
            if (showDebugInfo)
            {
                Debug.Log($"开始录制高光时刻: {moment.title}");
            }
            
            isRecording = true;
            
            // 模拟录制时间
            yield return new WaitForSeconds(moment.duration);
            
            // 模拟保存过程
            yield return new WaitForSeconds(1f);
            
            string fileName = $"{moment.id}.mp4";
            string filePath = Path.Combine(Application.persistentDataPath, highlightFolder, fileName);
            moment.filePath = filePath;
            moment.isSaved = true;
            
            isRecording = false;
            
            if (showDebugInfo)
            {
                Debug.Log($"高光时刻录制完成: {filePath}");
            }
            
            OnHighlightSaved?.Invoke(moment);
            
            // 自动分享
            if (autoShare)
            {
                ShareHighlight(moment);
            }
        }
    }
    
    void RemoveOldestHighlight()
    {
        if (highlights.Count > 0)
        {
            HighlightMoment oldest = highlights[0];
            highlights.RemoveAt(0);
            
            // 删除文件
            if (oldest.isSaved && !string.IsNullOrEmpty(oldest.filePath) && File.Exists(oldest.filePath))
            {
                File.Delete(oldest.filePath);
            }
            
            if (showDebugInfo)
            {
                Debug.Log($"移除最旧的高光时刻: {oldest.title}");
            }
        }
    }
    
    // 公共方法：手动触发高光时刻
    public void ManualTriggerHighlight(HighlightType type, string customTitle = "")
    {
        HighlightTrigger manualTrigger = new HighlightTrigger
        {
            triggerName = "Manual",
            type = type,
            enabled = true,
            priority = 0.5f,
            description = "手动触发的高光时刻"
        };
        
        TriggerHighlight(manualTrigger);
    }
    
    // 公共方法：获取所有高光时刻
    public List<HighlightMoment> GetAllHighlights()
    {
        return new List<HighlightMoment>(highlights);
    }
    
    // 公共方法：获取最佳高光时刻
    public HighlightMoment GetBestHighlight()
    {
        if (highlights.Count == 0) return null;
        
        HighlightMoment best = highlights[0];
        foreach (var highlight in highlights)
        {
            if (highlight.rating > best.rating)
            {
                best = highlight;
            }
        }
        
        return best;
    }
    
    // 公共方法：分享高光时刻
    public void ShareHighlight(HighlightMoment moment)
    {
        if (moment == null || !moment.isSaved)
        {
            OnHighlightError?.Invoke("无法分享未保存的高光时刻");
            return;
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"分享高光时刻: {moment.title}");
        }
        
        // 这里可以集成社交媒体分享功能
        // 例如：上传到云端、分享到社交平台等
    }
    
    // 公共方法：删除高光时刻
    public void DeleteHighlight(string highlightId)
    {
        HighlightMoment moment = highlights.Find(h => h.id == highlightId);
        if (moment != null)
        {
            highlights.Remove(moment);
            
            if (moment.isSaved && !string.IsNullOrEmpty(moment.filePath) && File.Exists(moment.filePath))
            {
                File.Delete(moment.filePath);
            }
            
            if (showDebugInfo)
            {
                Debug.Log($"删除高光时刻: {moment.title}");
            }
        }
    }
    
    // 事件处理方法
    void OnScoreChanged(int newScore)
    {
        CheckHighlightTriggers();
    }
    
    void OnPlayerDied()
    {
        // 检查是否有濒死逃脱的情况
        CheckHighlightTriggers();
    }
    
    void Update()
    {
        if (enableHighlights && autoCapture)
        {
            // 定期检查触发条件
            if (Time.frameCount % 30 == 0) // 每30帧检查一次
            {
                CheckHighlightTriggers();
            }
        }
    }
    
    void OnDestroy()
    {
        if (GameManager.Instance != null)
        {
            GameManager.Instance.OnScoreChanged -= OnScoreChanged;
            GameManager.Instance.OnPlayerDied -= OnPlayerDied;
        }
    }
    
    void OnDrawGizmos()
    {
        if (showDebugInfo)
        {
            // 在场景视图中显示录制状态
            Gizmos.color = isRecording ? Color.red : (enableHighlights ? Color.green : Color.gray);
            Gizmos.DrawWireSphere(transform.position, 1f);
            
            if (isRecording)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawWireCube(transform.position + Vector3.up, Vector3.one * 0.5f);
            }
        }
    }
}